package com.ywm;

import com.google.common.collect.Lists;
import com.ywm.common.generator.GeneratorTable;
import com.ywm.common.generator.JdbcUtil;
import com.ywm.common.utils.StrUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成类
 */
public class Generator {

	/**
	 * 自动代码生成
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String path = GeneratorTable.class.getResource("/").getPath().replace("/target/classes/", "").replaceFirst("/","");
		String basePath = path;
		String project = path.substring(path.lastIndexOf("/") + 1, path.length());
		try {
			Map<String, List<Map<String, String>>> map = new HashMap<String, List<Map<String, String>>>();
			Map table = new HashMap<>();
			String tb = "user";
			table.put("table_name", tb);
			table.put("model_name", StrUtils.lineToHump(tb));
			List<Map<String, String>> tables = new ArrayList<Map<String, String>>();
			tables.add(table);
			map.put("user", tables);
			GeneratorTable.generatorTabel(map, basePath, project);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// GeneratorTable.generatorTabel(genTables(), basePath, project);
	}

	public static Map<String, List<Map<String, String>>> genTables() throws SQLException {
		String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='yls_jz' and table_name not like 'bg_%' and table_name not in('promotion_channel')";
		JdbcUtil jdbcUtil = new JdbcUtil("com.mysql.jdbc.Driver",
				"jdbc:mysql://120.55.59.214:3306/yls_jz?useUnicode=true&characterEncoding=utf-8&autoReconnect=true",
				"yls_root", "yls2018");
		List<Map> result = jdbcUtil.selectByParams(sql, null);
		Map<String, List<Map<String, String>>> data = new HashMap<String, List<Map<String, String>>>();
		List<String> categoryList = Lists.newArrayList();
		for (Map tableMap : result) {
			String tableName = (String) tableMap.get("TABLE_NAME");
			Map table = new HashMap<>();
			int pri = tableName.indexOf("_");
			if (pri > 0) {
				String category = tableName.substring(0, tableName.indexOf("_"));
				if (!categoryList.contains(category)) {
					categoryList.add(category);
				}
			}
			table.put("table_name", tableName);
			table.put("model_name", StrUtils.lineToHump(tableName));
			List<Map<String, String>> tables = new ArrayList<Map<String, String>>();
			tables.add(table);
		}

		for (String pri : categoryList) {
			List<Map<String, String>> tables = new ArrayList<Map<String, String>>();
			for (Map map : result) {
				String tableName = (String) map.get("TABLE_NAME");
				if (tableName.startsWith(pri)) {
					Map table = new HashMap<>();
					table.put("table_name", tableName);
					table.put("model_name", StrUtils.lineToHump(tableName));
					tables.add(table);
				}
			}
			data.put(pri, tables);
		}
		return data;
	}

}
